package com.tianqu.tms.www.car.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsDaoException;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.security.TmsUserProfile;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.dto.MemberRentalLocationInfo;
import com.tianqu.tms.entity.Codes;
import com.tianqu.tms.entity.Member;
import com.tianqu.tms.entity.RentalContractInfo;
import com.tianqu.tms.www.car.actionform.CarPendingLiftActionForm;
import com.tianqu.tms.www.car.viewhelper.CarPendingLiftViewHelper;

/**
 * @author mufeiyu
 * 高级管理 - 信息录入 controller
 */
public class CarSeniorManagementModifyController extends TmsController {
	private Logger logger = Logger.getLogger(CarSeniorManagementModifyController.class);

	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		TxController controller = TxController.getTxController();		
		
		// 添加事务提交异常捕获
		try {
			controller.begin();
			CarPendingLiftViewHelper viewhelper = new CarPendingLiftViewHelper();
			CarPendingLiftViewHelper view = (CarPendingLiftViewHelper) uc.getAttribute(TmsConstants.VIEWHELP);
			CarPendingLiftActionForm form = (CarPendingLiftActionForm) uc.getInputForm();
			String memberId = view.getMemId();
			Member member = Member.getInstance();
			String deleteSerial = uc.getParameter("id");
			String rentalArea = uc.getParameter("rentalArea");

			if(!StringUtil.isNullOrBlank(deleteSerial)){
				member=member.findMemberInfoByMemId(memberId);							
				String businessNo = getBusinessNoStr(member.getBusinessNo(),deleteSerial);	
				String floors = getBusinessNoStr(member.getFloors(),rentalArea);
				TmsUserProfile profile = uc.getUserProfile();
				member.setUpdateUserId(profile.getUniqueId());
				member.setBusinessNo(businessNo);
				member.setFloors(floors);
				member.setMemId(Integer.valueOf(memberId));
				//合同编号List更新
				member.updateMemberBusinessNoInfo(member);
			}
			member=member.findMemberInfoByMemId(memberId);
			
			viewhelper = setDetailInfo(member,viewhelper,form);
			
			uc.setAttribute(TmsConstants.VIEWHELP, viewhelper);
			
			controller.commit();
		} catch (Exception e) {
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				throw e;
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}

		logger.debug(this.getClass().getName() + "#execute was completed.");
	}

	/**
	 * view赋值
	 * @return
	 */
	private CarPendingLiftViewHelper setDetailInfo(Member member,CarPendingLiftViewHelper viewhelper,CarPendingLiftActionForm form) throws TmsDaoException{
		Codes code = Codes.getInstance();
		 
		//商户编号
		viewhelper.setMemId(String.valueOf(member.getMemId()));
		//商户名称
		viewhelper.setMemName(member.getShortName());
		//商户状态
		if(member.getMemStatus()== 1){
			viewhelper.setMemStatus("正常");
		}else if(member.getMemStatus()== 2){
			viewhelper.setMemStatus("删除");
		}else if(member.getMemStatus()== 3){
			viewhelper.setMemStatus("禁用");
		}else{
			viewhelper.setMemStatus("");
		}
		viewhelper.setContractType(member.getContractType());
		viewhelper.setContractTime(member.getContractTime());
		//注册时间
		viewhelper.setInsertTime(member.getInsertTime());
		
		MemberRentalLocationInfo memberRentalLocationInfo = member.findMemberRentalLocationInfoCount(member.getBusinessNo());
		String unusedAnnualTransactionVolume = memberRentalLocationInfo.getUnusedAnnualTransactionVolume();
		String unusedCarPort = memberRentalLocationInfo.getUnusedCarPort();
		viewhelper.setUnusedAnnualTransactionVolume(StringUtil.getPointBetweenThree(StringUtils.isNotBlank(unusedAnnualTransactionVolume)?Integer.parseInt(unusedAnnualTransactionVolume):0));
		viewhelper.setUnusedCarPort(StringUtil.getPointBetweenThree(StringUtils.isNotBlank(unusedCarPort)?Integer.parseInt(unusedCarPort):0));
		//允许库存停放数量
		viewhelper.setCarPortStr(StringUtil.getPointBetweenThree(member.getCarPort()));
		//允许库存登记数量
		viewhelper.setAnnualTransactionVolume(StringUtil.getPointBetweenThree(member.getAnnualTransactionVolume()));
		
		//易碎贴免费数量
		viewhelper.setFragileStickerFreePort(StringUtil.getPointBetweenThree(member.getFragileStickerFreePort()));	
		//车源推荐权重
		List recommendListlist = code.getCodeslistByItemId(Codes.RECOMMEND_TYPE);
		viewhelper.setCarRecommendList(recommendListlist);
		viewhelper.setRecommend(member.getRecommend());
		//合同编号
		viewhelper.setSerial(form.getSerial());
		//租位编号
		viewhelper.setLocationSerial(form.getLocationSerial());
		//租位类型
		viewhelper.setRentalType(form.getRentalType());
		//租位面积
		viewhelper.setAcreage(form.getAcreage());
		//车位数量
		viewhelper.setRentalCarPort(form.getRentalCarPort());
		//
		viewhelper.setRentalAnnualTransactionVolume(form.getRentalAnnualTransactionVolume());
		//租位位置
		viewhelper.setAddress(form.getAddress());
		//开始时间
		viewhelper.setStartDate(form.getStartDate());
		//结束时间
		viewhelper.setEndDate(form.getEndDate());
		//租位按钮显示Flag
		viewhelper.setLocationAddBtnFlag(form.getLocationAddBtnFlag());
		
		//有效识别道闸
		viewhelper.setIdentityRangeList(convertIdentityRangeStr(member.getIdentityRange()));
		
		//临时识别道闸
		viewhelper.setTmpIdentityRangeList(convertIdentityRangeStr(member.getTmpIdentityRange()));
		
		//合同编号
		String businessNo = member.getBusinessNo();
		viewhelper.setBusinessNo(businessNo);
		List<RentalContractInfo> rentalList = new ArrayList<RentalContractInfo>(); 
		if(!StringUtil.isNullOrBlank(businessNo)){
			String[] list= businessNo.split(",");
			List<String> serialList = Arrays.asList(list);
			RentalContractInfo contractInfo = RentalContractInfo.getInstance();			
			for(int i=0;i<serialList.size();i++){
				contractInfo = contractInfo.findContractInfoBySerial(serialList.get(i));
				if(i%2 == 0){
					contractInfo.setCssFlag(1);
				}else {
					contractInfo.setCssFlag(2);
				}
				rentalList.add(contractInfo);
			}
		}
		//关联租位信息
		viewhelper.setRentalLocationInfoList(rentalList);
		
		return viewhelper;
	}
	
	private List convertIdentityRangeStr(String identityRangeCode) throws TmsDaoException{
		HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
		if(StringUtil.isNotBlank(identityRangeCode)){
			String[] tmp = identityRangeCode.split(",");
			for (int i = 0; i < tmp.length; i++){
				int itemCode = StringUtils.isNumeric(tmp[i])?Integer.parseInt(tmp[i]):-1;
				map.put(itemCode, itemCode);
			}
		}
		List codeslist = Codes.getInstance().getCodeslistByItemId(Codes.GATEWAY_TYPE);
		for (Object object : codeslist) {
			String checked = "";
			HashMap codesMap = (HashMap)object;
			if(map.get(codesMap.get("itemCode"))!=null ) checked = "checked";
			codesMap.put("checked", checked);
		}
		return codeslist;
	}
	
	/**
	 * 合同编号List取得
	 * 
	 * @param bussinessNo 合同编号List
	 * @param serial 合同编号
	 * @return
	 */
	private String getBusinessNoStr(String bussinessNo,String serial){
		String bussinessNoStr = "";
		if(!StringUtil.isNullOrBlank(bussinessNo)){
			String[] list= bussinessNo.split(",");
			List<String> serialList = new ArrayList<String>();
			for(int i=0;i<list.length;i++){
				serialList.add(list[i]);
			}
			for(int j=0;j<serialList.size();j++){
				if(serial.equals(serialList.get(j))){
					serialList.remove(j);
					break;
				}
			}
			if(serialList.size() > 0){
				bussinessNoStr = (String)serialList.get(0);
				for(int i=1;i<serialList.size();i++){
					bussinessNoStr = bussinessNoStr + "," + serialList.get(i);
				}
			}
		}
		return bussinessNoStr;
	}
}
